/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) GenSecKey.java 2018-08-06 17:26
 */

package cn.jh.common.core.crypto;

import org.inferred.freebuilder.FreeBuilder;


/**
 * @author Fuchun
 * @since 1.0
 */
@FreeBuilder
public abstract class GenSecKey implements GenKey {

    public static Builder aes() {
        return new Builder().setKeyAlg("AES").setKeySize(256);
    }

    public static Builder des3() {
        return new Builder().setKeyAlg("DESede").setKeySize(168);
    }

    private transient String cmdString = null;

    public static class Builder extends GenSecKey_Builder {

        public Builder() {
            setAlias("mykey");
            setStoreType("JCEKS");
            setView(false);
            setKeySize(-1);
        }

        @Override
        public GenSecKey build() {
            if (getKeyPass() == null) {
                setKeyPass(getStorePass());
            }
            int defaultKeySize;
            switch (getKeyAlg()) {
                case "AES":
                    defaultKeySize = 256; break;
                case "DES":
                    defaultKeySize = 56; break;
                case "DESede":
                    defaultKeySize = 168; break;
                    default:
                        throw new IllegalArgumentException("Not support `" + getKeyAlg() + "` algorithm.");
            }
            if (getKeySize() == -1) {
                setKeySize(defaultKeySize);
            }
            return super.build();
        }
    }

    @Override
    public String toCmdString() {
        if (cmdString != null) return cmdString;
        StringBuilder sb = new StringBuilder("-genseckey");
        sb.append(" -alias ").append(getAlias());
        sb.append(" -keypass ").append(getKeyPass());
        sb.append(" -keyalg ").append(getKeyAlg());
        sb.append(" -keysize ").append(getKeySize());
        sb.append(" -keystore ").append(getKeyStore());
        sb.append(" -storepass ").append(getStorePass());
        if (getStoreType() != null) {
            sb.append(" -storetype ").append(getStoreType());
        }
        appendProvider(sb);
        if (isView()) {
            sb.append(" -v");
        }
        cmdString = sb.toString();
        return cmdString;
    }
}
